using Unity.Entities;

namespace PathFinding
{
    public struct OptionalBufferAccessor<T> where T : unmanaged, IBufferElementData
    {
        BufferAccessor<T> m_BufferAccessor;
        BufferTypeHandle<T> m_TypeHandle;

        public DynamicBuffer<T> this[int index] => m_BufferAccessor.Length != 0 ? m_BufferAccessor[index] : default;

        public OptionalBufferAccessor(BufferTypeHandle<T> handle)
        {
            m_BufferAccessor = default;
            m_TypeHandle = handle;
        }

        public void Update(in ArchetypeChunk chunk)
        {
            if (chunk.Has<T>())
                m_BufferAccessor = chunk.GetBufferAccessor(ref m_TypeHandle);
        }

        public bool TryGetBuffer(int index, out DynamicBuffer<T> buffer)
        {
            if (m_BufferAccessor.Length == 0)
            {
                buffer = default;
                return false;
            }

            buffer = m_BufferAccessor[index];
            return true;
        }
    }
    
    /// <summary>
    /// Represents handle of NavMeshQuery used by <see cref="NavMeshQuerySystem"/>.
    /// </summary>
    public struct PathQueryHandle
    {
        /// <summary>
        /// Unique index of NavMesh query.
        /// </summary>
        public int Index;

        /// <summary>
        /// Invalid NavMesh query.
        /// </summary>
        public static PathQueryHandle Null => new PathQueryHandle();

        public static implicit operator int(PathQueryHandle handle) => handle.Index;
        public static bool operator ==(PathQueryHandle lhs, PathQueryHandle rhs) => lhs.Index == rhs.Index;
        public static bool operator !=(PathQueryHandle lhs, PathQueryHandle rhs) => lhs.Index != rhs.Index;

        public bool Equals(PathQueryHandle other) => other.Index == Index;

        public override bool Equals(object compare) => compare is PathQueryHandle compareNode && Equals(compareNode);

        public override int GetHashCode() => Index;
    }
}